# encoding: utf-8
# @File   : auth.py
# @Author : 乖孩子
# @Date   : 2025/07/24 16:29:34

import requests
import json
import os
from utils.http_client import HttpClient
from utils.file_handler import save_authorization


class AuthCore:
    def __init__(self, logger):
        self.logger = logger
        self.http_client = HttpClient(logger)

    def perform_login(self, server_ip, username, password, callback):
        """执行登录操作"""
        self.logger.info(f"开始登录请求 - 服务器: {server_ip}, 用户名: {username}")
        try:
            url = f"http://{server_ip}:4200/authority/users/login"
            headers = {
                "Content-Type": "application/json; charset=utf-8",
                "Connection": "keep-alive"
            }
            login_data = {
                "loginName": username,
                "password": password
            }

            success, response = self.http_client.post(url, headers=headers, data=login_data)

            if success and response.get('status_code') == 200:
                response_data = response.get('data', {})
                authorization = response_data.get('jwtToken', '')
                user_id = response_data.get('accountUserDefinedRoleRelations', [{}])[0].get('userID', '未知')

                # 保存认证信息
                save_path = save_authorization(authorization, response_data)

                self.logger.info(f"登录成功 - userID: {user_id}")
                callback(True, {
                    "status_code": 200,
                    "user_id": user_id,
                    "file_path": save_path
                })
            else:
                error_msg = response.get('message', '登录失败，未知错误')
                self.logger.error(f"登录失败: {error_msg}")
                callback(False, {"error": error_msg})

        except Exception as e:
            self.logger.exception(f"登录过程发生异常: {str(e)}")
            callback(False, {"error": f"发生异常: {str(e)}"})